<template>
  <c-form-dialog
    ref="form"
    :visible.sync="innerVisible"
    :table-name="tableName"
    :form-items="formItems"
    :form-data="formData"
    :before-save="handleBeforeSave"
    :table-id="tableId"
    @success="onsuccess"
    @close="handleClose"
    label-width="140px"
    :title="tableId ? '修改机构信息' : '新增机构'"
  ></c-form-dialog>
</template>

<script>
import { enumOrganLevel } from '@/credit/plugins/enum'
import SelectAddress from '@/components/select/SelectAddress'
// import { phoneValidator } from '@/common/plugins/validator'
import { mapGetters } from 'vuex'
import SelectAgencyInfo from '@/credit/components/select/SelectAgencyInfo'
import SelectSystemEnum from '@/cadmin/components/select/SelectSystemEnum'
import SelectOrgAuth from '@/cadmin/components/select/SelectOrgAuth'

export default {
  components: {},
  props: {
    visible: Boolean,
    formData: {
      type: Object,
      default: () => ({}),
    },
    tableId: String,
    orgType: {
      type: String,
      default: '6',
    },
  },
  data() {
    const nameValidator = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入机构名称'))
      } else if (!this.agencyName) {
        callback(new Error('机构名称已存在!'))
      } else {
        callback()
      }
    }
    const userValidator = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入登录账号'))
      } else if (!this.userName) {
        callback(new Error('名称已存在!'))
      } else {
        callback()
      }
    }
    return {
      innerVisible: false,
      formItems: [
        {
          tag: 'input',
          itemAttrs: {
            label: '机构名称',
            rules: [{ required: true, validator: nameValidator, trigger: 'blur' }],
          },
          attrs: { key: 'agency_name', value: '' },
          listeners: {
            change: this.promiseValidator,
          },
        },
        {
          tag: 'input',
          itemAttrs: {
            label: '合同编号-简称',
          },
          attrs: { key: 'short_name', value: '' },
        },
        {
          tag: SelectSystemEnum,
          itemAttrs: {
            label: '银行分类',
            rules: [{ required: true, message: '请选择银行分类', trigger: 'change' }],
          },
          attrs: {
            key: 'agency_type_sub',
            value: '',
            class: 'form-control-ml',
            type: 'bankClass',
            filterable: true,
          },
          ifRender: () => this.isOrgBank,
          events: {
            change: (model, v, label) => {
              model.parent_code = ''
              model.agency_type_sub_label = label
            },
          },
        },
        {
          tag: 'input',
          attrs: { key: 'agency_type_sub_label', value: '' },
          ifShow: false,
        },
        {
          tag: SelectAgencyInfo,
          itemAttrs: {
            label: '上级机构',
          },
          attrs: { key: 'parent_code', value: '', class: 'form-control-ml' },
          getAttrs: mode => {
            return { bankType: mode.agency_type_sub || '' }
          },
          ifRender: () => this.isOrgBank,
        },
        {
          tag: 'input',
          itemAttrs: {
            label: '账号名称',
            rules: [{ required: true, validator: userValidator, trigger: 'blur' }],
          },
          attrs: { key: 'user_name' },
          listeners: {
            input: this.userNameCheck,
            change: this.userChange,
          },
        },
        {
          tag: 'select',
          itemAttrs: {
            label: '行政级别',
            rules: [{ required: true, message: '请选择行政级别', trigger: 'change' }],
          },
          attrs: { clearable: false, key: 'org_region_lever', options: enumOrganLevel },
          ifRender: () => this.orgTypeNumber !== 2,
        },
        {
          tag: SelectSystemEnum,
          itemAttrs: {
            label: '机构级别',
            rules: [{ required: true, message: '请选择机构级别', trigger: 'change' }],
          },
          attrs: { key: 'lv_business', value: '', class: 'form-control-ml' },
          ifRender: () => this.orgTypeNumber === 2,
        },
        {
          tag: SelectAddress,
          itemAttrs: {
            label: '机构地址',
            rules: { required: true, message: '请选择机构地址', trigger: 'change' },
          },
          attrs: { key: 'address_code', value: '', class: 'form-control-ml' },
        },
        {
          tag: 'input',
          itemAttrs: { label: '详细地址' },
          attrs: { key: 'address_detail', value: '', placeholder: '请输入地址' },
        },
        {
          tag: 'input',
          itemAttrs: {
            label: '联系人',
            // rules: { required: true, message: '请输入联系人名称', trigger: 'blur' }
          },
          attrs: { key: 'contact', value: '', placeholder: '联系人名称' },
        },
        {
          tag: 'input',
          itemAttrs: {
            label: '联系电话',
            // rules: [
            //   { required: true, message: '请输入手机号码', trigger: 'blur' },
            //   { validator: phoneValidator, message: '请输入正确的手机号码', trigger: 'blur' }
            // ]
          },
          attrs: { key: 'mobile_no', value: '', placeholder: '联系电话' },
        },

        {
          tag: 'input',
          itemAttrs: {
            label: '法人',
            rules: { required: true, message: '请输入联系人名称', trigger: 'blur' },
          },
          attrs: { key: 'corp_name', value: '', placeholder: '法人名称' },
          ifRender: () => !this.isOrgBank,
        },
        {
          tag: 'input',
          itemAttrs: {
            label: '机构联系电话',
            rules: [
              // { required: true, message: '请输入机构联系电话', trigger: 'blur' },
              // { validator: phoneValidator, message: '请输入正确的手机号码', trigger: 'blur' },
            ],
          },
          attrs: { key: 'corp_mobile_no', value: '', placeholder: '联系电话' },
          ifRender: () => !this.isOrgBank,
        },
        {
          tag: 'input',
          itemAttrs: {
            label: '开户行',
          },
          attrs: { key: 'open_bank', value: '', placeholder: '开户行银行名称' },
          ifRender: () => this.isOrgCredit,
        },
        {
          tag: 'input',
          itemAttrs: {
            label: '户名',
          },
          attrs: { key: 'account_name', value: '', placeholder: '账户名称' },
          ifRender: () => this.isOrgCredit,
        },
        {
          tag: 'input',
          itemAttrs: {
            label: '账号',
          },
          attrs: { key: 'account_no', value: '', placeholder: '开户账号' },
          ifRender: () => this.isOrgCredit,
        },
        {
          tag: SelectOrgAuth,
          itemAttrs: {
            label: '机构权限',
          },
          attrs: { key: 'scopes', value: '', placeholder: '机构权限' },
          listeners: {
            change: (_, names) => {
              this.authNames = names
            },
          },
          getAttrs: () => {
            return { orgType: this.orgAuthType }
          },
          ifRender: () => this.orgTypeNumber !== 2,
        },
        {
          tag: 'input',
          attrs: { key: 'agency_id' },
          ifShow: false,
        },
      ],
      tableName: 'credit_agency_info',
      agencyName: true,
      userName: true,
      authNames: '',
    }
  },
  watch: {
    visible(val) {
      this.innerVisible = val
    },
    formData: {
      handler: function () {
        this.$refs.form.setAttrs('lv_business', { value: this.formData.org_region_lever })
      },
      deep: true,
    },
  },
  computed: {
    ...mapGetters(['clientId']),
    orgTypeNumber() {
      return +this.orgType
    },
    isOrgBank() {
      return this.orgTypeNumber === 1
    },
    isOrgCredit() {
      return this.orgTypeNumber === 6
    },
    orgAuthType() {
      return this.isOrgBank ? 'org_bank' : 'org_credit'
    },
  },
  created() {},
  methods: {
    userNameCheck(val) {
      const realName = val.replace(/[^A-Za-z0-9-_]+$/g, '')
      this.$refs.form.setAttrs('user_name', { value: realName })
    },
    promiseValidator(val) {
      if (!val) {
        return
      }
      this.$api.getData('credit', this.tableName, { 'agency_name.eq': val }).then(res => {
        const data = (res && res.data && res.data[0]) || {}

        if (data.agency_id && this.formData.agency_id !== data.agency_id) {
          this.agencyName = false
        } else {
          this.agencyName = true
        }
        this.$refs.form.validateField('agency_name')
      })
    },
    userChange(val) {
      if (!val) {
        return
      }
      this.$api.getData('credit', this.tableName, { 'user_name.eq': val }).then(res => {
        const data = (res && res.data && res.data[0]) || {}

        if (data.agency_id && this.formData.agency_id !== data.agency_id) {
          this.userName = false
        } else {
          this.userName = true
        }
        this.$refs.form.validateField('user_name')
      })
    },
    handleBeforeSave(data) {
      const { agency_id: agencyId, lv_business: lvBusiness, ...item } = data
      item.is_sync_sdb = 1
      item.service_id = this.clientId
      if (this.orgTypeNumber === 2) {
        item.org_region_lever = lvBusiness
      } else if (this.isOrgBank) {
        item.scopes_name = this.authNames
      }
      if (agencyId) {
        item.agency_id = agencyId
      }
      item.agency_type = this.orgType
      return item
    },
    handleClose() {
      this.agencyName = true
      this.userName = true
      this.$emit('update:visible', false)
    },
    onsuccess() {
      this.$emit('success', true)
    },
  },
}
</script>
<style lang="scss" scoped></style>
